功能:具有函式功能且一行就能使用,可接受任意數量的參數
double
def double(x):
return x * 2
print(double(10))
20
lambda λ改寫
double2 = lambda x: x*2
print(double2(50))
100
傳入多個參數
mutiply = lambda x, y: x * y
print(mutiply(5, 10))
50
if, else條件語句
result = lambdax: f"{x}是偶數" if x % 2 == 0 else f"{x}是奇數"
print(result(15))
15 是奇數
處理字串方式
full_name = lambda first_name, last_name: f"{first_name} {last_name}"
print(full_name("Jemmy", "Wang"))
Jemmy Wang
map(函式,可迭代列表[])
store = [
('襯衫‘, 20) #美元
('褲子', 30)
('夾克', 50)
('襪子', 10)
]
#美元轉歐元
to_euros = lambda date: (date[0], date[] * 0.82)
store_euros = list(map(to_euros, store))
print(store_euros)
[('襯衫', 16.4), ('褲子', 24.599999999999998), ('夾克', 41.0), ('襪子', 8.2)]
store = [
('襯衫‘, 600) #台幣
('褲子', 1200)
('夾克', 1600)
('襪子', 200)
]
#新台幣轉美金
to_usd = lambda date: (date[0], round(date[1] / 30)
store_usds = list(map(to_usd, store))
for item in store_usds:
print(item)
('襯衫', 20)
('褲子', 40)
('夾克', 53)
('襪子', 7)
功能:過濾可迭代的物件,如:列表list
friend = [
('Bob', 18)
('Steven', 17)
('Micheal', 19)
('Susan', 16)
]
age_filter = lambda date: date[1] >= 18
can_drink_friends = list(filter(age_filter, friend))
for friend in can_drink_friends:
print(friend[0])
print(friend[1])
Bob
18
Micheal
19